package main

import (
	"OldPackageTest/go_mysql/database/config"
	"log"
)

type user struct {
	Id   uint64 `json:id`
	Name string `json:"name"`
	Age  uint32 `json:age`
}

func querySingleRow() user {
	sqlStr := "select * from student where name =?"
	var u user
	if err := config.DB.QueryRow(sqlStr, 1).Scan(&u.Id, &u.Name, &u.Age); err != nil {
		log.Println("scan failed err : %v \n", err)
	}
	log.Println(u.Id, u.Name, u.Age)
	return u
}

func prepareQuery(name string) []user {
	sqlStr := "select * from student where name =?"
	stmt, _ := config.DB.Prepare(sqlStr)
	defer stmt.Close()

	rows, _ := stmt.Query(name)
	defer rows.Close()
	users := make([]user, 0)
	for rows.Next() {
		var u user
		err := rows.Scan(&u.Id, &u.Name, &u.Age)
		if err != nil {
			log.Println(err)
			return nil
		}
		users = append(users, u)
	}
	return users
}

func queryMultiRow() []user {
	sqlStr := "select * from student"
	rows, err := config.DB.Query(sqlStr)
	if err != nil {
		log.Println(err)
		return nil
	}
	defer rows.Close()
	users := make([]user, 0)
	for rows.Next() {
		var u user
		err := rows.Scan(&u.Id, &u.Name, &u.Age)
		if err != nil {
			log.Println(err)
			return nil
		}
		users = append(users, u)
	}
	return users
}
func main() {
	querySingleRow()
}
